package com.itbz.mapper;

import com.itbz.pojo.Users;
import com.itbz.util.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * 模糊查询测试类
 */
public class FuzzyQueryTest {
  /**
   * 根据用户名称模糊查找用户信息
   */
  public List<Users> fuzzyQuery(String username){
    List<Users> list= new ArrayList<>();


    Connection conn =null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try{
      //获取数据库连接
      conn = JdbcUtils.getConnection();
      //创建PreparedStatement对象
      ps = conn.prepareStatement("select * from users where username like ?");
      //参数绑定
      ps.setString(1,username);
      //执行sql语句
      rs = ps.executeQuery();
      while(rs.next()){
        Users user = new Users();
        user.setUserid(rs.getInt("userid"));
        user.setUsername(rs.getString("username"));
        user.setUserage(rs.getInt("userage"));
        list.add(user);
       }
     }catch(Exception e){
      e.printStackTrace();
     }finally{
      JdbcUtils.closeResource(rs,ps,conn);
     }
    return list;
   }


  public static void main(String[] args) {
    FuzzyQueryTest ft = new FuzzyQueryTest();
    List<Users> users = ft.fuzzyQuery("%张%");
    for(Users user1:users){
      System.out.println(user1.getUserid()+" "+user1.getUsername()+" "+user1.getUserage());
     }
   }
}
